package com.violet.mvpdemo.page

import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.violet.constlib.Status
import com.violet.mvpdemo.mvp.viewmodel.MainViewModel
import com.violet.mvpdemo.mvp.MainContact
import com.violet.themvp.BaseDiAct
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@AndroidEntryPoint
class MainActivity : BaseDiAct<MainContact.Delegate>() {

    private val mViewModel by viewModels<MainViewModel>()

    init {
        load()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.e("lifecycleScope", "onCreate")
        super.onCreate(savedInstanceState)
    }

    override fun initData() {
        super.initData()
        //通过协程加载
        mViewModel.launchUser().observe(this, {
            when(it.status) {
                Status.LOADING -> showLoading()
                else -> {
                    hideLoading()
                    viewDelegate.setText(it.data?:"")
                }
            }
        })

//        mViewModel.test()
    }


    private fun load() {
        //lifecycle STARTED 才会调用
        lifecycleScope.launchWhenStarted {

            //ui 代码
            Log.e("lifecycleScope",  "协程")

            val user: String
            //异步代码
            withContext(Dispatchers.IO) {
                //执行异步代码
                delay(1000) //模拟网络请求
                user = ""
            }

            //继续执行ui代码
            print(user)

        }
    }

}